package cn.doctorpda.conference.presenter;

import org.json.JSONException;
import org.json.JSONObject;

import cn.doctorpda.conference.MyApplication;
import cn.doctorpda.conference.bean.Msg;
import cn.doctorpda.conference.bean.User;
import cn.doctorpda.conference.config.AppConfig;
import cn.doctorpda.conference.config.NetConfig;
import cn.doctorpda.conference.localstore.ClientInfo;
import cn.doctorpda.conference.localstore.UserInfo;
import cn.doctorpda.conference.model.GetRegisterModel;
import cn.doctorpda.conference.model.GetVerifyCodeLoginModel;
import cn.doctorpda.conference.model.IPostModel;
import cn.doctorpda.conference.okhttp.callback.StringCallback;
import cn.doctorpda.conference.utils.AESUtil;
import cn.doctorpda.conference.utils.GsonUtil;
import cn.doctorpda.conference.utils.L;
import cn.doctorpda.conference.view.callbackview.IBaseView;
import cn.doctorpda.conference.view.callbackview.ILoginView;
import cn.doctorpda.conference.view.callbackview.IRegisterView;
import okhttp3.Call;

/**
 * Created by huangjinlong on 2016/5/19.
 */
public class VerifyCodeLoginPresenter {
    private IPostModel model;
    private ILoginView loginCodeView;

    public VerifyCodeLoginPresenter(ILoginView baseView) {
        model = new GetVerifyCodeLoginModel();
        loginCodeView = (ILoginView) baseView;
    }

    public void getVerifyCodeLogin(String number, String verifyCode) {
        model.postNetWorkStringData(NetConfig.GET_VERIFYCODE_LOGIN, new StringCallback() {
            @Override
            public void onError(Call call, Exception e) {
                loginCodeView.setLoginError(call, e);
            }

            @Override
            public void onResponse(String response) {
                try {
                    Msg msg = GsonUtil.fromJson(response, Msg.class);
                    loginCodeView.setILoginToast(msg);
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.getString("encrpt_flag").equals("1")) {
                        String data = AESUtil.decrypt(msg.getData(), AppConfig.AES_KEY);
                        JSONObject object = new JSONObject(data);
                        User user = GsonUtil.fromJson(object.getString("account").toString(), User.class);
                        ClientInfo.setUserAccessToken(MyApplication.getInstance(), object.getString("access_token"));
                        UserInfo.saveUserInfo(user);
                        loginCodeView.setLoginResult(msg, user);
                    } else {
//                        loginView.setResult(msg, user);
                        L.d(msg.getData());
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, number, verifyCode);
    }
}
